package TwoAgain;

import java.io.*;
import java.time.LocalDate;
import java.util.TreeSet;

public class FileControlImpl implements IFileControl{
    @Override
    public void read(TreeSet<Employee> treeSet, String path) {
        Reader r = null;
        BufferedReader br = null;

        try {
            r = new FileReader(path);
            br = new BufferedReader(r);

            String str = null;
            while ((str = br.readLine())!=null){
                String[] array = str.split("\\s+");
                Employee e = new Employee(array[0],array[1], LocalDate.parse(array[2]),Integer.parseInt(array[3]));
                treeSet.add(e);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                r.close();
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void write(TreeSet<Employee> treeSet, String path) {
        Writer w = null;

        try {
            w = new FileWriter(path);
            for (Employee e:treeSet){
                w.write(e.getCode()+"  "+e.getName()+"  "+e.getData()+"  "+e.getSalary()+"\n");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                w.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
